package com.lxc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxc.entity.BusinessException;
import com.lxc.entity.Result;
import com.lxc.entity.Works;
import com.lxc.mapper.WorkMapper;
import com.lxc.service.WorkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.lxc.util.saveImageToFileSystem;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WorkServiceImpl extends ServiceImpl<WorkMapper, Works> implements WorkService {
    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /*

        @Autowired
        private CategoryMapper categoryMapper;

        @Autowired
        private WorkCategoriesMapper workCategoriesMapper;
    */
    @Override
    /*在redis查询没有的话就去mysql查询并更新到redis*/
    public Works getWorkById(Integer id) {
        if (id == null){
            throw new BusinessException(400, "作品ID不能为空");
        }
        /*redis缓存小说*/
        String cacheKey = "work:detail:" + id;
        // 先查 Redis
        Works work = (Works) redisTemplate.opsForValue().get(cacheKey);

        /*Redis缓存浏览量 + 定期持久化*/
        String key = "work:view:" + id;
        redisTemplate.opsForValue().increment(key);

        if (work == null) {
            // 未命中则查数据库
            work = workMapper.getWorkById(id);
            if (work != null) {
                // 设置缓存过期时间（例如5分钟）
                redisTemplate.opsForValue().set(cacheKey, work, 5, TimeUnit.MINUTES);
            }
        }

        return work;
    }

    /*定时更新浏览量*/
    //@Scheduled(cron = "0 0/5 * * * ?") // 每分钟执行一次
    @Scheduled(cron = "0 * * * * ?") //没秒执行一次
    public void syncViewsToDatabase() {
        Set<String> keys = redisTemplate.keys("work:view:*");
        if (keys == null || keys.isEmpty()) return;

        for (String key : keys) {
            try {
                // 提取 novelId（int）
                String idStr = key.split(":")[2];
                int novelId = Integer.parseInt(idStr);

                // 获取当前缓存中的 view 数量
                 Integer viewsToAdd = (Integer) redisTemplate.opsForValue().get(key);
                if (viewsToAdd == null || viewsToAdd <= 0) continue;

                // 更新数据库
                workMapper.addViews(novelId, viewsToAdd.intValue());

                // 清除缓存或保留用于累计
                redisTemplate.delete(key); // 或者改为 opsForValue().set(key, 0, ...)

            } catch (Exception e) {
                // 打印完整异常日志
                log.error("同步浏览量失败，key={}", key, e);
                throw new BusinessException(500, "同步失败"+e.getMessage());
            }
        }
    }


    @Override
    /*查询所有著作*/
    public IPage<Works> getWorks(String name, String category, Integer pageNum, Integer pageSize) {

        IPage<Works> page=new Page<>(pageNum, pageSize);
        return workMapper.getWorks(page, name, category,pageNum,pageSize);
    }


    public void updateWork(Works work) {
        workMapper.updateById(work);

        // 删除缓存
        String detailCacheKey = "work:detail:" + work.getId();
        String listCacheKeyPrefix = "works:list:";

        Set<String> keys = redisTemplate.keys(listCacheKeyPrefix + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);  // 清除所有列表缓存（可按业务更精细化处理）
        }
        redisTemplate.delete(detailCacheKey);
    }
    @Override
    public Works addwork(Works works, MultipartFile file) throws IOException {

        // 1. 检查作品是否已存在（根据标题判断）
        String title = works.getName();
        if (title == null || title.isEmpty()) {
            throw new BusinessException(400, "作品标题不能为空");
        }

        QueryWrapper<Works> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", title); // 根据 title 查询是否已存在

        if (this.getOne(queryWrapper) != null) {
            throw new BusinessException(400, "作品《" + title + "》已存在");
        }

        // 1. 文件上传逻辑
        String filePath;
        filePath = saveImageToFileSystem.save(file); // 改为静态方法调用

        // 2. 设置封面路径到作品对象
        works.setWorkPicture(filePath);

        // 3. 保存作品信息到数据库
        int success = workMapper.insert(works);
        if (success >0) {
            return works;
        } else {
            throw new BusinessException(500, "作品添加失败");
        }
    }

    @Override
    public boolean deleteById(Integer id) {
        int i=workMapper.deleteById(id);
        if (i>0){
            return true;
        }
        else{
            throw new BusinessException(500, "删除失败");
        }
    }


}